<!--
 * @Descripttion: 配送单凭证明细表
 * @version:
 * @Author: lehaixia
 * @Date: 2021-10-30 09:43:54
 * @LastEditors: lehaixia
 * @LastEditTime: 2021-12-23 10:54:54
-->
<template>
  <!-- <div :class="$style.deliveryTable"> -->
  <div class="deliveryTable">
    <ContentWrap>
      <FormContainer :column="3">
        <el-form ref="form" :model="formData" :rules="formRules" label-width="80px">
          <el-form-item prop="officeCode" label="办事处">
            <SearchSelectPicker
              url="/call-center/api/v1/mscInfo/office/ref/page"
              placeholder="请选择办事处"
              lable-name="name"
              value-name="code"
              method="get"
              :value.sync="formData.officeCode"
              @selectChange="officeChangeHandle"
            ></SearchSelectPicker>
          </el-form-item>
          <el-form-item prop="disCode" label="经销商名称">
            <SearchSelectPicker
              url="/call-center/api/v1/mscInfo/dealer/ref/page"
              method="get"
              placeholder="请选择经销商"
              :params="{query:{officeCode:formData.officeCode},type:0}"
              lable-name="name"
              value-name="code"
              custom-name="codeOrName"
              must-pid
              :disabled="!formData.officeCode"
              :parent-id="formData.officeCode"
              :value.sync="formData.disCode"
            ></SearchSelectPicker>
          </el-form-item>
          <el-form-item prop="scheduleCode" label="排工单号">
            <el-input v-model="formData.scheduleCode" placeholder="请输入排工单号" clearable />
          </el-form-item>
          <el-form-item prop="consigneeName" label="顾客姓名">
            <el-input v-model="formData.consigneeName" placeholder="请输入顾客姓名" clearable />
          </el-form-item>
          <el-form-item prop="consigneePhone" label="顾客电话">
            <el-input v-model="formData.consigneePhone" placeholder="顾客电话" clearable />
          </el-form-item>
          <el-form-item prop="date" label="完成日期">
            <el-date-picker
              v-model="formData.date"
              type="daterange"
              value-format="yyyy-MM-dd"
              :limite="new Date()"
              operator=">"
              opt
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            />
          </el-form-item>
          <el-form-item prop="isShowVoucher" label="是否上传凭证">
            <el-select
              v-model="formData.isShowVoucher"
              placeholder="请选择"
              clearable
              filterable
              style="width:100%"
            >
              <el-option value="1" label="已上传" />
              <el-option value="0" label="未上传" />
            </el-select>
          </el-form-item>
          <el-form-item prop="deliveryType" label="订单类型">
            <el-select v-model="formData.deliveryType" filterable clearable multiple placeholder="请选择订单类型">
              <el-option v-for="(item, index) of deliveryTypeList" :key="index" :value="item.dictCode" :label="item.dictName" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <Button @click="$refs.form.resetFields()">重置</Button>
            <Button type="primary" enter @click="queryHandle">查询</Button>
          </el-form-item>
        </el-form>
      </FormContainer>
      <div class="button-container" style="padding-top:0">
        <Button type="primary" @click="handleExportConfigCredentials">凭证图片下载</Button>
        <Button type="primary" @click="handleExportComments">评价图片下载</Button>
        <!-- <Button type="primary" @click="handleExportForm">导出</Button> -->
        <ExportPane :table-config="tableConfigExport" :other-raw="otherRaw" :data-source="selectedAry" :query-data-fun="queryHandle" filename="配送凭证明细表">导出</ExportPane>
      </div>
      <table-box
        ref="table"
        no-request
        :table-config="tableConfig"
        :other-filters="otherFilters"
        :other-raw="otherRaw"
        @selection-change="selectionChange"
        @data-change="loading=false"
      >
        <el-table-column slot="before" type="selection" align="center" width="50"></el-table-column>
      </table-box>
      <export-image
        v-if="showCredentialsExport"
        title="凭证图片下载"
        :visible.sync="showCredentialsExport"
        :config="exportConfigCredentials"
      />
      <export-image
        v-if="showCommentsExport"
        title="评价图片下载"
        :visible.sync="showCommentsExport"
        :config="exportConfigComments"
      />
      <!-- 导出 -->
      <!-- <export-files
        v-if="showExport"
        title="导出"
        :visible.sync="showExport"
        :config="exportConfig"
      /> -->
    </ContentWrap>
  </div>
</template>
<script>
import ContentWrap from '@/components/ContentWrap'
import FormContainer from '@/components/FormContainer'
import Button from '@/components/Button'
import ExportPane from '@/components/ExportPane'
import SearchSelectPicker from '@/components/SearchSelectPicker'
import PreviewImageVideo from '@/components/PreviewImageVideo'
import ExportImage from '../orderEvaluate/components/exportImage'
import { filtersRaw, deepCopy } from '@/utils'
import { ccDict } from '@/api/dataDict'

export default {
  name: 'OrderEvaluateTable',
  components: {
    ContentWrap,
    FormContainer,
    Button,
    ExportPane,
    SearchSelectPicker,
    ExportImage
  },
  data() {
    return {
      loading: false,
      otherFilters: [],
      otherRaw: {},
      formData: {
        officeCode: '',
        disCode: '',
        consigneeName: '',
        consigneePhone: '',
        scheduleCode: '',
        date: [],
        isShowVoucher: '',
        deliveryType: ''
      },
      formRules: {},
      tableConfig: {
        interfacePath: '/call-center/api/v1/reportAppraiseDetail/delivery/page',
        // sort: 'installedTime',
        hideFuncBar: true,
        // 表格字段动态配置
        setting: [{
          prop: 'officeCode',
          width: 110,
          label: '办事处编码'
        }, {
          prop: 'officeName',
          width: 140,
          label: '办事处'
        }, {
          prop: 'disCode',
          label: '经销商编码',
          width: 110
        }, {
          prop: 'disName',
          width: 140,
          label: '经销商名称'
        }, {
          prop: 'scheduleCode',
          width: 160,
          label: '排工单号'
        }, {
          prop: 'deliveryType',
          width: 120,
          label: '订单类型',
          propEnum: {
            appCode: 'call-center',
            domainCode: 'marketing',
            dictTypeCode: 'CC_ORDER_TYPE'
          }
        }, {
          prop: 'customerName',
          width: 120,
          label: '顾客姓名'
        }, {
          prop: 'customerPhone',
          width: 120,
          label: '顾客电话'
        }, {
          prop: 'artificerName',
          width: 120,
          label: '送装技师'
        }, {
          prop: 'artificerPhone',
          width: 120,
          label: '联系电话'
        }, {
          prop: 'serviceAttitude',
          width: 120,
          label: '服务态度',
          formatData: v => {
            return ((v.serviceAttitude || 0) / 2).toFixed(2)
          }
        }, {
          prop: 'serviceSpeed',
          width: 120,
          label: '送装速度',
          formatData: v => {
            return ((v.serviceSpeed || 0) / 2).toFixed(2)
          }
        }, {
          prop: 'serviceQuality',
          width: 120,
          label: '安装质量',
          formatData: v => {
            return ((v.serviceQuality || 0) / 2).toFixed(2)
          }
        }, {
          prop: 'overallSatisfaction',
          width: 140,
          label: '综合满意度',
          formatData: v => {
            return ((Number(v.serviceAttitude || 0) + Number(v.serviceSpeed || 0) + Number(v.serviceQuality || 0)) / 2 / 3 - (v.companyScore || 0)).toFixed(2)
          }
        }, {
          prop: 'voucher',
          width: 120,
          label: '凭证图片',
          align: 'center',
          render: (h, row) => {
            if ((row.voucher || []).length > 0) {
              const voucher = row.voucher && row.voucher.map(item => (/^marketing/.test(item.filePath) ? process.env.VUE_APP_FILE_PREFIX : `/upload/`) + item.filePath)
              return <el-image class='table-image' preview-src-list={voucher} src={voucher[0]}></el-image>
            }
            return <span>无</span>
          }
        }, {
          prop: '',
          width: 140,
          label: '评价图片或视频',
          align: 'center',
          render: (h, row) => {
            if ((row.annexes || []).length > 0) {
              const annexes = deepCopy(row.annexes)
              return <PreviewImageVideo prefix='/upload/' annexes={annexes}></PreviewImageVideo>
            }
            <return span>无</return>
          }
        }, {
          prop: 'installedTime',
          width: 140,
          label: '完成日期'
        // }, {
        //   prop: '',
        //   width: 140,
        //   label: '评价图片',
        //   align: 'center',
        //   render: (h, row) => {
        //     if ((row.annexes || []).length > 0) {
        //       const annexes = deepCopy(row.annexes)
        //       return <PreviewImageVideo prefix='/upload/' annexes={annexes}></PreviewImageVideo>
        //     }
        //     <return span>无</return>
        //   }
        }]
      },
      deliveryTypeList: [], // 订单类型列表
      showCredentialsExport: false,
      exportConfigCredentials: [{
        code: 'credentials', // 导出编码，前段定义，同一个config中code不能重复
        name: '凭证图片', // 导出名称，如：商品导出，导出用户
        dataApi: `/call-center/api/v1/reportAppraiseDetail/batchDownloadVouchers`, // 导出数据的接口地址
        selectedRows: [], // 当前所选中的数据行
        queryField: ['disCode', 'customerName', 'scheduleCode', 'voucher']// 指定行导出的字段名称
      }],
      showCommentsExport: false,
      exportConfigComments: [{
        code: 'comments', // 导出编码，前段定义，同一个config中code不能重复
        name: '评价图片', // 导出名称，如：商品导出，导出用户
        dataApi: `/call-center/api/v1/reportAppraiseDetail/batchDownloadAttachments`, // 导出数据的接口地址
        selectedRows: [], // 当前所选中的数据行
        queryField: ['disCode', 'customerName', 'scheduleCode', 'annexes']// 指定行导出的字段名称
      }],
      showExport: false, // 导出弹出框标识
      exportConfig: [{
        code: 'delivery', // 导出编码，前段定义，同一个config中code不能重复
        name: '配送单凭证明细表', // 导出名称，如：商品导出，导出用户
        async: false, // 是否异步
        dataApi: `/call-center/api/v1/reportAppraiseDetail/delivery/export`, // 导出数据的接口地址
        filtersRaw: [], // filter查询参数
        paramsRaw: {}, // params查询参数
        selectedRows: [], // 当前所选中的数据行
        queryField: 'id'// 指定行导出的字段名称
      }],
      tableConfigExport: {
        interfacePath: '/call-center/api/v1/reportAppraiseDetail/delivery/export',
        // sort: 'installedTime',
        hideFuncBar: true,
        // 表格字段动态配置
        setting: [{
          prop: 'officeCode',
          width: 110,
          label: '办事处编码'
        }, {
          prop: 'officeName',
          width: 140,
          label: '办事处'
        }, {
          prop: 'disCode',
          label: '经销商编码',
          width: 110
        }, {
          prop: 'disName',
          width: 140,
          label: '经销商名称'
        }, {
          prop: 'scheduleCode',
          width: 160,
          label: '排工单号'
        }, {
          prop: 'deliveryType',
          width: 120,
          label: '订单类型',
          propEnum: {
            appCode: 'call-center',
            domainCode: 'marketing',
            dictTypeCode: 'CC_ORDER_TYPE'
          }
        }, {
          prop: 'customerName',
          width: 120,
          label: '顾客姓名'
        }, {
          prop: 'customerPhone',
          width: 120,
          label: '顾客电话'
        }, {
          prop: 'artificerName',
          width: 120,
          label: '送装技师'
        }, {
          prop: 'artificerPhone',
          width: 120,
          label: '联系电话'
        }, {
          prop: 'serviceAttitude',
          width: 120,
          label: '服务态度',
          formatData: v => {
            return ((v.serviceAttitude || 0) / 2).toFixed(2)
          }
        }, {
          prop: 'serviceSpeed',
          width: 120,
          label: '送装速度',
          formatData: v => {
            return ((v.serviceSpeed || 0) / 2).toFixed(2)
          }
        }, {
          prop: 'serviceQuality',
          width: 120,
          label: '安装质量',
          formatData: v => {
            return ((v.serviceQuality || 0) / 2).toFixed(2)
          }
        }, {
          prop: 'overallSatisfaction',
          width: 140,
          label: '综合满意度',
          formatData: v => {
            return ((Number(v.serviceAttitude || 0) + Number(v.serviceSpeed || 0) + Number(v.serviceQuality || 0)) / 2 / 3 - (v.companyScore || 0)).toFixed(2)
          }
        }, {
          prop: 'installedTime',
          width: 140,
          label: '完成日期'
        }]
      },
      selectedAry: [],
      // 图片导出
      fields: {
        annexes: {
          label: '图片',
          formatData: row => {
            if (row.annexes && row.annexes.length > 0) {
              return row.annexes.map(e => e.annexePath).join(',')
            }
            return ''
          }
        }
      }
    }
  },
  created() {
    this.getDeliveryTypeList()
  },
  methods: {
    // 获取订单类型字典
    getDeliveryTypeList() {
      ccDict('CC_ORDER_TYPE').then(res => {
        this.deliveryTypeList = res.data
      })
    },
    // 办事处变化
    officeChangeHandle() {
      this.$set(this.formData, 'disCode', '')
    },
    // 查询
    queryHandle(type) {
      // 日期和派工单号必选一个
      if (this.formData.scheduleCode === '' && (!this.formData.date || this.formData.date.length <= 0)) {
        this.$message.info('日期和派工单号必选一个！')
        return Promise.reject()
      }
      return this.$refs.form.validate().then(() => {
        const list = []
        const otherRaw = {}
        const eq = ['officeCode', 'disCode', 'scheduleCode', 'consigneeName', 'consigneePhone']
        // eslint-disable-next-line prefer-const
        for (let [k, v] of Object.entries(this.formData)) {
          if (v === '' || v === undefined || v === null || (v instanceof Array && v.length <= 0)) {
            continue
          }
          if (k === 'isShowVoucher' && v) {
            otherRaw.isShowVoucher = v
            continue
          }

          if (k === 'date') {
            // otherRaw.startDate = v[0]
            // otherRaw.endDate = v[1]
            console.log(v[1])
            list.push(filtersRaw('installedTime', `${v[0]} 00:00:00`, '>='))
            list.push(filtersRaw('installedTime', `${v[1]} 23:59:59`, '<='))
            continue
          }
          if (v instanceof Array && k !== 'deliveryType') {
            v = v.join(',')
          }

          if (v instanceof Array && k === 'deliveryType') {
            v = `[${v.join(',')}]`
          }

          if (eq.includes(k)) {
            list.push(filtersRaw(k, v, '='))
          } else if (k === 'deliveryType') {
            list.push(filtersRaw(k, v, 'in'))
          } else {
            list.push(filtersRaw(k, v, 'like'))
          }
        }
        this.otherFilters = list
        this.otherRaw = otherRaw
        if (type !== 'export') {
          this.refreshTable()
        }
        return list
      })
    },
    // 刷新表格
    refreshTable(type) {
      this.$nextTick(() => {
        this.$refs.table.initTableData(type)
      })
    },
    // 表格选中事件
    selectionChange(val) {
      this.selectedAry = val
    },
    // 凭证图片下载
    handleExportConfigCredentials() {
      if (this.selectedAry.length === 0) {
        return this.$message.info('请至少选择一条数据')
      }
      this.showCredentialsExport = true
      const exportConfig = this.exportConfigCredentials[0]
      exportConfig.selectedRows = this.selectedAry || []

      this.$set(this.exportConfigCredentials, 0, exportConfig)
    },
    // 评论图片下载
    handleExportComments() {
      if (this.selectedAry.length === 0) {
        return this.$message.info('请至少选择一条数据')
      }
      this.showCommentsExport = true
      const exportConfig = this.exportConfigComments[0]
      exportConfig.selectedRows = this.selectedAry || []

      this.$set(this.exportConfigComments, 0, exportConfig)
    },
    // 导出
    handleExportForm() {
      const exportConfig = this.exportConfig[0]
      exportConfig.filtersRaw = this.otherFilters
      exportConfig.selectedRows = this.selectedAry || []
      exportConfig.paramsRaw = this.otherRaw

      this.$set(this.exportConfig, 0, exportConfig)
      this.$nextTick(() => {
        this.showExport = true
      })
    }
  }
}
</script>
<style lang='scss' scoped>
 .deliveryTable {
  tr{
    background-color: white !important;
  }
}

  .table-image {
    margin: 5px;
    max-width: 100%;
    max-height: 50px;
    object-fit: cover;
    vertical-align: middle;
  }

   /deep/ .el-image-viewer__btn {
    display: flex !important;
  }
</style>
